package com.baidu.roomdemo.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.LiveData
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.baidu.roomdemo.databinding.LayoutUserItemBinding
import com.baidu.roomdemo.db.User
import com.baidu.roomdemo.fragment.ListFragmentDirections

class UserAdapter:RecyclerView.Adapter<UserAdapter.MyViewHolder>() {
    private var mUserDatas:List<User> = emptyList()

    class MyViewHolder(val binding: LayoutUserItemBinding ): RecyclerView.ViewHolder(binding.root){
        fun bind(user: User){
            binding.tvNumber.text = user.id.toString()
            binding.tvFirstName.text = user.firstName
            binding.tvLastName.text = user.lastName
            binding.tvAge.text = user.age.toString()

            //添加点击事件
            binding.root.setOnClickListener {
                //切换到编辑页面
                val navController = binding.root.findNavController()
                //切换
                val direction = ListFragmentDirections.actionListFragmentToUpdateFragment(user)
                navController.navigate(direction)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = LayoutUserItemBinding.inflate(inflater, parent, false)
        return MyViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return mUserDatas.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(mUserDatas[position])
    }

    //设置数据源
    fun setData(datas: List<User>){
        mUserDatas = datas
        notifyDataSetChanged()
    }
}